import type { Instruction } from '@/types/AIResponse'
import { ElMessage } from 'element-plus'
import {
  handleAddFeature,
  handleUpdateFeature,
  handleRemoveFeature,
  handleCreateBuffer,
  handleQueryFeature,
  handleQuerySurrounding,
} from './mapOperations'
import {
  handleMeasureDistance,
  handleMeasureArea,
  handleHeatmapGeneration,
  handleGenerateReport,
} from './mapAnalysisOperations'
import { useInstructionResultStore } from '@/stores/modules/instructionResult'

// 生成唯一的指令ID
const generateInstructionId = () => {
  return Date.now().toString() + Math.random().toString(36).substring(2, 10)
}

// 执行地图操作
export const executeMapOperation = async (
  instruction: Instruction,
  view: __esri.MapView,
  sketchViewModel: __esri.SketchViewModel,
  tempGraphic: __esri.Graphic | null,
  setTempGraphic: (graphic: __esri.Graphic) => void,
  setCurrentInstruction: (instruction: Instruction) => void,
  initFeatureFormData: (layerType: string, aiAttributes: any) => void,
  setFeatureFormTitle: (title: string) => void,
  setFeatureFormVisible: (visible: boolean) => void,
  featureFormVisible: boolean,
  featureFormData: any,
  setFeatureFormData: (data: any) => void,
  setAttributes: (attrs: any) => void,
  setDialogTitle: (title: string) => void,
  setDialogVisible: (visible: boolean) => void,
  highlightHandle: __esri.Handles,
) => {
  // 获取指令结果存储
  const instructionResultStore = useInstructionResultStore()
  // 生成唯一的指令ID
  const instructionId = generateInstructionId()
  // 初始化结果数据
  let resultData: any = null
  // 初始化状态
  let status: 'success' | 'failed' = 'success'
  // 初始化错误信息
  let errorMessage: string | undefined = undefined
  try {
    switch (instruction.action) {
      case 'ADD_FEATURE':
        const addResult = await handleAddFeature(
          instruction,
          view,
          sketchViewModel,
          tempGraphic,
          setTempGraphic,
          setCurrentInstruction,
          initFeatureFormData,
          setFeatureFormTitle,
          setFeatureFormVisible,
          featureFormVisible,
          featureFormData,
        )
        // 保存添加要素结果
        resultData = {
          attributes: instruction.params.attributes,
          geometry: addResult?.geometry || null,
        }
        break
      case 'UPDATE_FEATURE':
        let updateResult: any = await handleUpdateFeature(
          instruction,
          view,
          featureFormData,
          setFeatureFormData,
          setFeatureFormTitle,
          setFeatureFormVisible,
          featureFormVisible,
        )
        // 保存更新要素结果
        resultData = {
          attributes: updateResult?.attributes || instruction.params.attributes,
          updatedFeatureId: updateResult?.objectId,
        }
        break
      case 'REMOVE_FEATURE':
        const removeResult: any = await handleRemoveFeature(instruction, view)
        // 保存删除要素结果
        resultData = {
          attributes: instruction.params.attributes,
          deletedFeatureIds: removeResult?.objectIds || [],
        }
        break
      case 'CREATE_BUFFER':
        const bufferResult: any = await handleCreateBuffer(instruction, view)
        // 保存缓冲区结果
        resultData = {
          bufferParams: instruction.params.bufferParams,
          geometry: bufferResult?.geometry || null,
        }
        break
      case 'QUERY_FEATURE':
        const queryResult = await handleQueryFeature(
          instruction,
          view,
          setAttributes,
          setDialogTitle,
          setDialogVisible,
          highlightHandle,
        )
        // 保存查询结果，包含详细的地理信息
        resultData = {
          attributes: queryResult?.attributes || {},
          queryParams: instruction.params.queryParams,
          geometryInfo: queryResult?.geometryInfo || null,
          features: queryResult?.features || [],
        }
        console.log('查询结果', queryResult)
        break
      case 'MEASURE_DISTANCE':
        await handleMeasureDistance(instruction, view)
        break
      case 'MEASURE_AREA':
        await handleMeasureArea(instruction, view)
        break
      case 'HEATMAP_GENERATION':
        await handleHeatmapGeneration(instruction, view)
        break
      case 'GENERATE_REPORT':
        await handleGenerateReport(
          instruction,
          view,
          setAttributes,
          setDialogTitle,
          setDialogVisible,
        )
        break
      case 'QUERY_SURROUNDING':
        const surroundingResult = await handleQuerySurrounding(
          instruction,
          view,
          setAttributes,
          setDialogTitle,
          setDialogVisible,
        )
        // 保存周边查询结果，包含详细的地理信息
        resultData = {
          poiList: surroundingResult?.poiList || [],
          surroundingParams: instruction.params.surroundingParams,
          centerPoint: surroundingResult?.centerPoint || null,
          poiPoints: surroundingResult?.poiPoints || [],
        }
        break
      default:
        ElMessage.error('未知指令类型')
    }
  } catch (error: any) {
    console.error('操作失败:', error)
    ElMessage.error(`操作失败: ${error}`)
    // 设置失败状态和错误信息
    status = 'failed'
    errorMessage = error.message || String(error)
  } finally {
    // 无论成功或失败，都保存指令执行结果
    // 在存储前对结果数据进行序列化处理，移除不可序列化的属性
    const safeResultData = resultData
      ? JSON.parse(
          JSON.stringify(resultData, (key, value) => {
            // 过滤掉ArcGIS特殊属性或不可序列化的对象
            if (key === '__accessor__' || typeof value === 'function' || key.startsWith('_')) {
              return undefined
            }
            return value
          }),
        )
      : null

    instructionResultStore.addResult({
      instructionId,
      action: instruction.action,
      layerType: instruction.layerType,
      executedAt: Date.now(),
      status,
      resultData: safeResultData,
      errorMessage,
    })
  }
}

// 处理指令队列
export const processInstructionQueue = async (
  queue: Instruction[],
  isProcessing: boolean,
  setIsProcessing: (value: boolean) => void,
  isViewActive: boolean,
  executeMapOperation: (instruction: Instruction) => Promise<void>,
) => {
  if (queue.length > 0 && !isProcessing && isViewActive) {
    console.log('开始执行指令队列')
    setIsProcessing(true)
    try {
      while (queue.length > 0) {
        console.log('执行指令', queue[0])
        const instruction = queue[0]
        await executeMapOperation(instruction)
        console.log('指令执行完毕', instruction)
        queue.shift() // 使用数组的 shift 方法安全移除指令
      }
    } catch (error) {
      console.error('执行指令队列出错:', error)
      ElMessage.error(`执行指令队列出错: ${error}`)
    } finally {
      console.log('指令队列执行完毕')
      setIsProcessing(false) // 确保在所有指令处理完毕后才设置为false
    }
  }
}
